package com.bolt.support.dynamic.datasource.toolkit;

import com.bolt.common.collection.MapUtil;
import com.bolt.common.reflect.ClassUtil;
import com.bolt.common.utils.StrUtil;
import com.bolt.support.dynamic.datasource.autoconfigure.DataSourceProperty;
import com.bolt.support.dynamic.datasource.autoconfigure.DynamicDataSourceProperties;
import org.hibernate.dialect.Dialect;

import java.util.HashMap;
import java.util.Map;

public class DialectContextHolder {

    private static Map<String, Dialect> DIALECTS = new HashMap<>();

    private static String primary = "master";

    public static void initialize(DynamicDataSourceProperties properties) {
        primary = properties.getPrimary();
        Map<String, DataSourceProperty> dataSourcePropertyMap = properties.getDatasource();
        for (String key : dataSourcePropertyMap.keySet()) {
            DataSourceProperty dataSourceProperty = dataSourcePropertyMap.get(key);
            String dialect = dataSourceProperty.getDialect();
            if (StrUtil.isNotBlank(dialect)) {
                DIALECTS.put(key, ClassUtil.newInstance(dialect));
            }
        }
    }

    public static Dialect getCurrentDialect() {
        if (MapUtil.isNotEmpty(DIALECTS)) {
            String key = TenantContextHolder.peek();
            key = StrUtil.isBlank(key) ? primary : key;
            Dialect dialect = DIALECTS.get(key);
            return dialect != null ? dialect : DIALECTS.values().iterator().next();
        } else {
            throw new RuntimeException("Dialect config not initialize");
        }
    }
}